import javax.media.jai.JAI;
import javax.media.jai.RenderedOp;
import javax.media.jai.PlanarImage;
import java.awt.image.renderable.ParameterBlock;
import com.sun.media.jai.codec.ImageEncoder;
import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.JPEGEncodeParam;
import java.io.OutputStream;
import java.io.FileOutputStream;

public class ImageEncoder {
  
  public void outputImage(String filepath, OutputStream out, String format) throws Exception {
    if ("BMP".equals(format)) {
      RenderedOp src = JAI.create("fileload", filepath);
      JAI.create("encode", src, out, format, null);
    } else if ("JPG".equals(format) || "JPEG".equals(format)) {
      ParameterBlock pb = (new ParameterBlock()).add(filepath);
      PlanarImage src = JAI.create("fileload", pb);
      JPEGEncodeParam encodeParam = new JPEGEncodeParam();
      encodeParam.setWriteJFIFHeader(true);
      ImageEncoder encoder = ImageCodec.createImageEncoder("JPEG", out, encodeParam);
      encoder.encode(src);
    }
  }
  
  public static void main(String[] argv) throws Exception {
    String filename = argv[0];
    FileOutputStream fos = new FileOutputStream(argv[1]); 
    ImageEncoder t = new ImageEncoder();
    t.outputImage(filename, fos, argv[2]);
    fos.close();
  }
    
}